import { useState, useEffect } from 'react';
import { Base64 } from 'js-base64';
import cookie from 'js-cookie';
import { message } from 'antd';
import _ from 'lodash';

//  邮箱验证
const checkEmails = email => {
    const reg = new RegExp('^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$');
    return reg.test(email.toLowerCase());
};

// 发送邮件
const useSendMail = params => {
    const [loading, setLoading] = useState(false);
    const [isSuccess, setIsSuccess] = useState(null);
    const [resultMsg, setResultMsg] = useState(null);

    const send = async () => {
        const user = JSON.parse(localStorage.getItem('user') || '{}');
        const { email, employeeName } = user;

        const formData = new FormData();
        const { to, cc, subject, content, uploadFiles = [] } = params;

        if (_.isEmpty(to) || _.isEmpty(subject) || _.isEmpty(content)) {
            message.error('收件人、主题、正文都不能为空');
            return false;
        }
        const toArr = to.split(',');
        // 验证收件人邮箱地址
        for (let i = 0; i < toArr.length; i += 1) {
            if (!checkEmails(toArr[i])) {
                message.error(`收件人： ${toArr[i]} 邮箱格式错误！`);
                return false;
            }
        }
        if (!_.isEmpty(cc)) {
            const ccArr = cc.split(',');
            // 验证抄送人邮箱地址
            for (let i = 0; i < ccArr.length; i += 1) {
                if (!checkEmails(ccArr[i])) {
                    message.error(`抄送人： ${ccArr[i]} 邮箱格式错误！`);
                    return false;
                }
            }
            formData.append('cc', cc);
        }

        formData.append('userName', localStorage.getItem('currentMail') || email);

        formData.append('to', to);

        formData.append('subject', subject);

        formData.append('content', Base64.encode(content));

        formData.append('fromName', employeeName);

        uploadFiles.forEach(file => {
            formData.append('files', file);
        });

        setLoading(true);
        return fetch('/api/mail/v1/inbox/sendmail', {
            method: 'POST',
            headers: {
                Authorization: cookie.get('Authorization')
            },
            body: formData
        })
            .then(res => res.json())
            .then(res => {
                if (res.code === 10000) {
                    setIsSuccess(true);
                    setResultMsg('邮件发送成功');
                    message.success('邮件发送成功');
                } else {
                    setIsSuccess(null);
                    setResultMsg(res.msg);
                    message.error(res.msg);
                }
            })
            .finally(() => {
                setLoading(false);
            });
    };

    useEffect(() => {
        if (params) {
            send();
        }
    }, [params]);

    return {
        loading,
        isSuccess,
        resultMsg,
        method: {
            resetSuccess() {
                setResultMsg(null);
                setIsSuccess(null);
            }
        }
    };
};

export default useSendMail;
